<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\model\ExamineRecord;
use addons\qingdongams\model\Consume as ConsumeModel;
use addons\qingdongams\model\Message;
use think\Db;
use think\Exception;

/**
 * 费用接口
 */
class Consume extends StaffApi
{
    protected $noNeedLogin = [];
    protected $noNeedRight = [];


    //添加费用
    public function addConsume()
    {
        $params = $this->request->post();

        // 表单验证
        if (($result = $this->qingdongamsValidate($params,get_class(), 'create')) !== true) {
            $this->error($result);
        }

        Db::startTrans();
        try {
            $lastId = ConsumeModel::createConsume($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('添加费用成功',['id'=>$lastId]);
        }
    }

    //编辑费用
    public function editConsume()
    {
        $params = $this->request->post();

        // 表单验证
        if (($result = $this->qingdongamsValidate($params, get_class(),'create')) !== true) {
            $this->error($result);
        }
        Db::startTrans();
        try {
            $result = ConsumeModel::updateConsume($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('编辑费用成功');
        }
    }

    //获取待审批费用数量
    public function getConsumeNumber()
    {

        $faqi = ConsumeModel::where([
            'staff_id' => $this->auth->id,
            'check_status' => ['in', [0, 1]]
        ])->count();
        $shenpi = ConsumeModel::where([
            'check_status' => ['in', [0, 1]],
        ])->where([])->count();

        $this->success('请求成功', ['faqi' => $faqi, 'shenpi' => $shenpi]);
    }

    //获取费用列表
    public function getList()
    {
        $limit = input("limit/d", 10);
        $customer_id = input('customer_id', '', 'intval');
        //发起人 查询
        $staff_id = input('staff_id', '', 'intval');
        $name = input('name', '', 'intval');

        $check_status = input('check_status');//1审核中、2审核通过、3审核未通过
        $relation_type = input('relation_type');//
        $relation_id = input('relation_id');//
        $ids=input('ids');
        $type = input('type', 1);
        $whereFlow = $followWhere = [];
        $where = [];
        $times = input('times', '');


        if ($check_status) {
            //0待审核、1审核中、2审核通过、3审核未通过、4撤销
            if ($check_status == 1) {
                $where['check_status'] = ['in', [0, 1]];
                $followWhere[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',check_staff_ids)')];
            } elseif ($check_status == 2) {
                $where['check_status'] = 2;
                $followWhere[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',check_staff_ids)')];
            } elseif ($check_status == 3) {
                $where['check_status'] = 3;
                $followWhere[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',check_staff_ids)')];
            }elseif ($check_status == 4) {
                $where['check_status'] = 4;
                $followWhere[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',check_staff_ids)')];
            }elseif ($check_status == 9) {
                $where['check_status'] = 9;
                $followWhere[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',check_staff_ids)')];
            }
        }
        if ($type == 1) {//我发起的
            $where['staff_id'] = $this->auth->id;
        } elseif ($type == 2) {//我审批的
            $whereFlow = $followWhere;
        }elseif ($type == 3 && empty($ids)){
            $this->success('请求成功',[]);
        }
        if ($ids) {
            $where['id'] = ['in',explode(',',$ids)];
        }
        if ($customer_id) {
            $where['customer_id'] = $customer_id;
            if(isset($where['staff_id']))unset($where['staff_id']);
        }
        if ($name) {
            $where['number'] = ["like","%{$name}%"];
        }
        if ($staff_id) {
            $where['staff_id'] = $staff_id;
        }
        if ($relation_type) {
            $where['relation_type'] = $relation_type;
            unset($where['staff_id']);
        }
        if ($relation_id) {
            $where['relation_id'] = $relation_id;
        }
        if ($times) {
            $times = setTimes($times, 'time');
            $where['createtime'] = ['between', $times];
        }
        $records = ConsumeModel::where($where)->where($whereFlow)->with(['staff', 'customer','consume_detail'])->order('id desc')->paginate($limit);
        $this->success('请求成功', $records);
    }


    //获取费用详情
    public function getDetail()
    {
        $id = input('id', '', 'intval');
        $consume = ConsumeModel::where(['id' => $id])
            ->with(['staff', 'customer','consume_detail'])->find();
        if (empty($consume)) {
            $this->error('费用不存在');
        }
        if($consume['staff_id'] == $this->auth->id && $consume['check_status'] != 2){
            $consume['is_edit'] = 1;
        }else{
            $consume['is_edit'] = 0;
        }
        $consume['is_operation']=0;
        if($consume['staff_id'] == $this->auth->id){
            //是否可以操作
            $consume['is_operation']=1;
        }


        if ($consume['check_status'] == 0 || $consume['check_status'] == 1) {
            $consume['is_examine'] = ExamineRecord::isExaminse(ExamineRecord::CONSUME_TYPE, $id);
        } else {
            $consume['is_examine'] = 0;
        }
        //标记通知已读
        Message::setRead(Message::CONSUME_TYPE, $id, $this->auth->id);

        $this->success('请求成功', $consume);
    }

    //撤销费用
    public function cancelConsume()
    {
        $id = input('id');
        if(empty($id)){
            $this->error('id不能为空');
        }
        $consume=ConsumeModel::where(['id'=>$id])->find();
        if(empty($consume)){
            $this->error('信息不存在');
        }
        if($consume['staff_id'] != $this->auth->id){
            $this->error('只有创建人可以撤销费用');
        }
        Db::startTrans();
        try {
            ConsumeModel::where(['id'=>$id])->update(['check_status'=>4]);
            ExamineRecord::cancelExaminse( ExamineRecord::CONSUME_TYPE,$id);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('撤销成功');
    }
    //终止费用
    public function revokeConsume()
    {
        $id = input('id');
        if(empty($id)){
            $this->error('id不能为空');
        }
        $consume=ConsumeModel::where(['id'=>$id])->find();
        if(empty($consume)){
            $this->error('信息不存在');
        }
        if($consume['staff_id'] != $this->auth->id){
            $this->error('只有创建人可以终止费用');
        }
        Db::startTrans();
        try {
            ConsumeModel::where(['id'=>$id])->update(['check_status'=>9]);
            ExamineRecord::cancelExaminse( ExamineRecord::CONSUME_TYPE,$id);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('终止费用');
    }


    //费用计算
    public function consume_count(){
        $number=input('number');

        $this->success('请求成功',['money'=>ConsumeModel::getMileageMoney($number)]);
    }

    //获取费用编号
    public function getNumber()
    {
        $this->success('请求成功', ['number' => ConsumeModel::getNumber()]);
    }

    //获取出纳列表
    public function getCashierList()
    {
        $limit = input("limit/d", 10);
        $customer_id = input('customer_id', '', 'intval');
        //发起人 查询
        $staff_id = input('staff_id', '', 'intval');

        $ids=input('ids');
        $name=input('name');
        $is_cashier = input('is_cashier', NULL);
        $where = ['check_status'=>2];

        if ($ids) {
            $where['id'] = ['in',explode(',',$ids)];
        }
        if ($name) {
            $where['number'] = ["like","%{$name}%"];
        }
        if ($customer_id) {
            $where['customer_id'] = $customer_id;
        }
        if ($staff_id) {
            $where['staff_id'] = $staff_id;
        }
        if($is_cashier!==NULL){
            $where['is_cashier'] = $is_cashier;
        }
        $records = ConsumeModel::where($where)->with(['staff', 'customer','consume_detail'])->order('id desc')->paginate($limit);
        $this->success('请求成功', $records);
    }

    //出纳
    public function cashier(){
        $ids=input('ids');
        if(empty($ids)){
            $this->error('参数错误');
        }
        $ids=explode(',',$ids);
        ConsumeModel::where(['id'=>['in',$ids]])->update(['is_cashier'=>1]);
        $data=[];
        foreach ($ids as $id){
            $data[] = [
                'relation_type' => ExamineRecord::CONSUME_TYPE,
                'relation_id' => $id,
                'check_staff_id' => $this->auth->id,
                'status' => 1,
                'content' => '出纳审核',
                'createtime' => time(),
                'updatetime' => time()
            ];
        }
        $examineModel=new ExamineRecord();
        $examineModel->insertAll($data);

        $this->success('操作成功');
    }

}
